package Arrays;

public class _840_MagicSquaresInGrid {
    public int numMagicSquaresInside(int[][] grid) {
        int count = 0;
        int length = grid.length;
        int width = grid[0].length;
        for (int r = 0; r < length - 2; r++) {
            for (int c = 0; c < width - 2; c++) {
                if (magic(grid[r][c], grid[r][c+1], grid[r][c+2],
                        grid[r+1][c], grid[r+1][c+1], grid[r+1][c+2],
                        grid[r+2][c], grid[r+2][c+1], grid[r+2][c+2]))
                    count++;
            }
        }
        return count;
    }

    public boolean magic(int... vals) {
        int[] count = new int[16];
        for (int val : vals) {
            count[val]++;
        }
        for(int i=1;i<=9;i++) {
            if (count[i] != 1) {
                return false;
            }
        }
        return (vals[0] + vals[1] + vals[2] == 15 &&
                vals[3] + vals[4] + vals[5] == 15 &&
                vals[6] + vals[7] + vals[8] == 15 &&
                vals[0] + vals[3] + vals[6] == 15 &&
                vals[1] + vals[4] + vals[7] == 15 &&
                vals[2] + vals[5] + vals[8] == 15 &&
                vals[0] + vals[4] + vals[8] == 15 &&
                vals[2] + vals[4] + vals[6] == 15);
    }
}
